package com.example.springboot.controller.httpcache;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/31 15:12
 */
@RestController
@RequestMapping("/czk/http")
public class HttpCacheController {
    @PostMapping("/cache")
    public ResponseEntity cache(@RequestHeader(value = "If-Modified-Since", required = false)
                                        String ifModifiedSinceStr) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date ifModifiedSince = dateFormat.parse(ifModifiedSinceStr);

        long lastModifiedDate = getLastModifiedDate(ifModifiedSince);//获取文档最后更新时间
        long now = System.currentTimeMillis();
        int maxAge = 30; //数据在浏览器端缓存30秒
        // 判断文档是否被修改过
        if (Objects.nonNull(ifModifiedSince) && ifModifiedSince.getTime() == lastModifiedDate) {

            // 文档没有被修改过
            HttpHeaders headers = new HttpHeaders();
            headers.add("Date", dateFormat.format(new Date(now))); //设置当前时间
            headers.add("Expires", dateFormat.format(new Date(now + maxAge * 1000))); //设置过期时间
            headers.add("Cache-Control", "max-age=" + maxAge);
            return new ResponseEntity(headers, HttpStatus.NOT_MODIFIED);
        }
        //文档已经被修改过
        HttpHeaders headers = new HttpHeaders();
        headers.add("Date", dateFormat.format(new Date(now))); //设置当前时间
        headers.add("Last-Modified", dateFormat.format(new Date(lastModifiedDate))); //设置最近被修改的日期
        headers.add("Expires", dateFormat.format(new Date(now + maxAge * 1000))); //设置过期时间
        headers.add("Cache-Control", "max-age=" + maxAge);

        String responseBody = JSON.toJSONString(ImmutableMap.of("website", "https://silently9527.cn"));
        return new ResponseEntity(responseBody, headers, HttpStatus.OK);
    }

    /**
     * 获取上一次修改的时间
     *
     * @param ifModifiedSince
     * @return
     */
    private long getLastModifiedDate(Date ifModifiedSince) {
        long now = System.currentTimeMillis();
        if (Objects.isNull(ifModifiedSince)) {
            return now;
        }
        long seconds = (now - ifModifiedSince.getTime()) / 1000;
        if (seconds > 15) {
            return now;
        }
        return ifModifiedSince.getTime();
    }
}
